import { defineStore } from 'pinia'
import router from '@/router'
import { LocationQueryRaw, RouteParamsRaw } from 'vue-router'
import { handleTree } from '@/utils'
import Layout from '@/layout/Index.vue'
import { getAllMenuTree, getMenuTreeById } from '@/apis/system/menu'
import { userStore } from './user.store'
import { shallowRef } from 'vue'
import { storage } from './sessionStorage'
import { currentUserInformation } from '@/apis/login/login'

//vite // 首先把你需要动态路由的组件地址全部获取
const modules = import.meta.glob('../pages/**/*Index.vue')

// console.log('modules', modules)
/**
 * 定义顶部菜单路由信息接口
 */
export interface HeaderRouterInterface {
    path: string
    title: string
    activePath?: string
    hidden?: boolean
    params?: object
    query?: object
}

/**
 * 定义state中所有信息类型
 */
export interface routers {
    headerRouters: Array<HeaderRouterInterface>
    selectIndex: number
    defaultActivePath: string
    permission: string[]
    menu: any[]
    routeArray: any[]
    tree: any[]
}

/**
 * 定义action中所有方法
 */
type actionType = {
    setPermissionRouter: () => any
    setHeaderRouter: () => any
    removeHeaderRoute: () => any
    contextOperate: () => any
    fillterData: () => any
    resetData: () => any
}

interface metaInterface {
    title: string
    hidden?: boolean
    activePath?: string
    icon?: string
}
interface routeType {
    path?: string
    name?: string
    component?: any
    redirect?: string
    children?: routeType[]
    meta?: metaInterface
    sort?: number
    type?: number
    parentId?: string
    parentName?: string
    title?: string
}

export const bubbleSort = (list: any[]) => {
    const len = list.length
    if (len < 2) {
        return list
    }
    for (let i = 0; i < len; i++) {
        if (list[i].children && list[i].children.length) {
            list[i].children = bubbleSort(list[i].children)
        }
        for (let j = 0; j < i; j++) {
            if (list[j].sort > list[i].sort) {
                const temp = list[j]
                list[j] = list[i]
                list[i] = temp
            }
        }
    }
    return list
}

export const routerStore = defineStore('routerStore', {
    state: (): routers => {
        return {
            headerRouters: [{ path: '/index', title: '首页' }],
            selectIndex: 0,
            defaultActivePath: '/index',
            permission: [],
            menu: [],
            routeArray: [],
            tree: []
        }
    },
    actions: {
        resetData() {
            this.permission.length = 0
            this.menu.length = 0
            this.routeArray.length = 0
            this.tree.length = 0

            //删除多余的导航
            if (this.headerRouters.length > 1) {
                this.headerRouters.splice(1, this.headerRouters.length - 1)
            }
        },
        /**
         * h获取路由及权限
         * @returns
         */
        async getDynamicPermission() {
            return new Promise((resolve, reject) => {
                //拉取用户信息，并保存company、companyId
                currentUserInformation().then((info: any) => {
                    if (info.data.value === 200) {
                        const _userStore = userStore()
                        _userStore.companyId = info.data.data.companyId
                        _userStore.company = info.data.data.companyName
                        _userStore.userId = info.data.data.id
                        _userStore.isSuperAdmin = info.data.data.isSuperAdmin
                        _userStore.phone = info.data.data.phone
                        _userStore.name = info.data.data.name
                        if (info.data.data.isSuperAdmin) {
                            //超级管理员
                            getAllMenuTree().then(result => {
                                this.fillterData(result as any[], (arr: any[]) => {
                                    resolve(arr)
                                })
                            })
                        } else {
                            //非超级管理员
                            getMenuTreeById(info.data.data.id).then(result => {
                                this.fillterData(result.data.data, (arr: any[]) => {
                                    resolve(arr)
                                })
                            })
                        }
                    } else {
                        reject()
                    }
                })
            })
        },
        fillterData(result: any[], callback: (arr: any[]) => void) {
            const list: any[] = result

            //权限
            const permissionArray: any[] = []
            //路由
            const menuArray: any[] = []

            list.forEach(item => {
                item.type === 2 ? permissionArray.push(item) : menuArray.push(item)
            })

            permissionArray.forEach(item => {
                this.permission.push(item.code)
            })

            console.log('permissionArray', permissionArray)

            const menuTree: any[] = handleTree(menuArray, 'id', 'parentId')

            this.routeArray.length = 0
            this.routeArray.push(...setTree(menuTree))
            this.menu.length = 0
            this.menu.push(...bubbleSort(setTree(menuTree, false)))
            callback(this.routeArray)
            // console.log('menu', this.menu)
            // console.log('routeArray', this.routeArray)
        },

        /**
         * 设置顶部路由菜单
         * @param target
         */
        setHeaderRouter(target: HeaderRouterInterface) {
            let has = false
            // console.log('target', target)

            //判断传递 target 的路由路径是否存在 this.headerRouters 中
            this.headerRouters.forEach((item: HeaderRouterInterface, index: number) => {
                if (item.path == target.path) {
                    has = true
                    item.title = target.title
                    item.params = target.params
                    item.path = target.path
                    item.query = target.query
                    item.activePath = target.activePath
                    item.hidden = target.hidden
                    this.selectIndex = index
                }

                if (item.path === '/system/menu/edit') {
                    if (JSON.stringify(target.query) == '{}') {
                        const query = JSON.parse('menuParams')[0]
                        item.title = query.type == 'create' ? '新增菜单' : '菜单编辑'
                    } else {
                        const query = JSON.parse(JSON.stringify(target.query))
                        item.title = query.type == 'create' ? '新增菜单' : '菜单编辑'
                    }
                } else if (item.path === '/system/notice/edit') {
                    // console.log('公告消息', JSON.stringify(target.query))
                    if (JSON.stringify(target.query) == '{}') {
                        // console.log(item.title, target.title)
                    } else {
                        const query = JSON.parse(JSON.stringify(target.query))
                        item.title = query.type == 'create' ? '新增消息' : '消息编辑'
                    }
                }
            })

            //不存在
            if (!has) {
                //设置顶部菜单当前选中的下标
                this.selectIndex = this.headerRouters.length

                //添加到 this.headerRouters
                this.headerRouters.push(target)
            }

            //并设置左侧默认路由地址
            this.defaultActivePath = target.hidden ? (target.activePath as string) : target.path
        },

        /**
         * 删除顶部菜单
         * @param index
         */
        removeHeaderRoute(index: number): void {
            if (index === this.selectIndex) {
                //删除的下标等于选中的下标

                //设置选中下标
                this.selectIndex = index - 1

                //设置选中路径
                this.defaultActivePath = this.headerRouters[this.selectIndex].path

                //从 this.headerRouters 中删除
                this.headerRouters.splice(index, 1)

                //页面进行跳转
                if (this.selectIndex === 0) {
                    router.push({
                        path: '/index',
                        query: {},
                        params: {}
                    })
                } else {
                    router.push({
                        path: this.headerRouters[this.selectIndex].path,
                        query: (this.headerRouters[this.selectIndex].query as LocationQueryRaw) ?? undefined,
                        params: (this.headerRouters[this.selectIndex].params as RouteParamsRaw) ?? undefined
                    })
                }
            } else if (index < this.selectIndex) {
                //删除的下标小于选中的下标，设置选中的下标等于删除的下标

                this.selectIndex = this.selectIndex - 1

                //从 this.headerRouters 中删除
                this.headerRouters.splice(index, 1)
            } else {
                //删除的下标大于选中的下标 直接从 this.headerRouters 中删除
                this.headerRouters.splice(index, 1)
            }

            //遍历当前数组，判断是否存在
            //判断编辑菜单页面是否存在
            let hasMenuEditExist = false
            this.headerRouters.forEach((item: HeaderRouterInterface, index: number) => {
                if (item.path === '/system/menu/edit') {
                    hasMenuEditExist = true
                }
            })
            //不存在，删除本地菜单数据
            if (!hasMenuEditExist) {
                storage.remove('menuParams')
            }
        },

        /**
         *
         * @param type
         * @param menu
         */
        contextOperate(type: string, index: number) {
            // console.log(type, 'index', index, 'selectIndex', this.selectIndex)
            if (type === 'all') {
                //关闭全部页面，跳转到首页
                router.push({
                    path: '/index',
                    query: {},
                    params: {}
                })
                this.headerRouters.splice(1, this.headerRouters.length - 1)
            } else if (type === 'current') {
                //关闭当前页面
                this.removeHeaderRoute(index)
            } else if (type === 'right') {
                //关闭右侧菜单页面
                this.headerRouters.splice(index + 1, this.headerRouters.length - index - 1)
                if (index < this.selectIndex) {
                    this.selectIndex = index
                    if (index === 0) {
                        router.push({
                            path: '/index',
                            query: {},
                            params: {}
                        })
                    } else {
                        router.push({
                            path: this.headerRouters[this.selectIndex].path,
                            query: (this.headerRouters[this.selectIndex].query as LocationQueryRaw) ?? undefined,
                            params: (this.headerRouters[this.selectIndex].params as RouteParamsRaw) ?? undefined
                        })
                    }
                }
            } else if (type === 'left') {
                //关闭左侧菜单页面
                this.headerRouters.splice(1, index - 1)
                if (index <= this.selectIndex) {
                    this.selectIndex = this.selectIndex - (index - 1)
                    router.push({
                        path: this.headerRouters[this.selectIndex].path,
                        query: (this.headerRouters[this.selectIndex].query as LocationQueryRaw) ?? undefined,
                        params: (this.headerRouters[this.selectIndex].params as RouteParamsRaw) ?? undefined
                    })
                } else {
                    this.selectIndex = this.selectIndex - (index - 1)
                    router.push({
                        path: '/index',
                        query: {},
                        params: {}
                    })
                }
                console.log(this.selectIndex)
            } else if (type === 'other') {
                //关闭其它页面
                if (index === 0) {
                    this.headerRouters.splice(1, this.headerRouters.length - 1)
                    this.selectIndex = 0
                    router.push({
                        path: '/index',
                        query: {},
                        params: {}
                    })
                } else {
                    this.headerRouters.splice(index + 1, this.headerRouters.length - index - 1)
                    this.headerRouters.splice(1, index - 1)
                    this.selectIndex = 1
                    router.push({
                        path: this.headerRouters[this.selectIndex].path,
                        query: (this.headerRouters[this.selectIndex].query as LocationQueryRaw) ?? undefined,
                        params: (this.headerRouters[this.selectIndex].params as RouteParamsRaw) ?? undefined
                    })
                }
            } else if (type === 'reload') {
                //刷新当前页面
                router.go(0)
            }
        }
    }
})

/**
 * 设置路由结构树
 * @param arr
 * @param isRouter
 * @returns
 */
const setTree = (arr: any[], isRouter = true) => {
    const result: routeType[] = []
    arr.forEach(item => {
        const route: routeType = {}
        route.meta = {
            title: item.name,
            icon: item.icon,
            hidden: false
        }
        route.name = item.code
        route.path = item.url
        route.children = []
        route.sort = item.sort
        route.type = item.type
        route.parentId = item.parentId
        route.parentName = item.parentName
        route.title = item.name

        if ('children' in item) {
            route.component = isRouter ? shallowRef(Layout) : ''
            route.children.push(...setTree(item.children, isRouter))
        } else {
            // console.log(`../pages${item.component}/Index.vue`)
            route.component = isRouter ? shallowRef(modules[`../pages${item.component}/Index.vue`]) : ''
        }

        result.push(route)
    })
    return result
}
